/*
 * io.c - 
 */

#include <io.h>

/**************/
/** Screen  ***/
/**************/

#define NUM_COLUMNS 80
#define NUM_ROWS    25

Byte x, y=15;

/* Read a byte from 'port' */
Byte inb (unsigned short port)
{
  Byte v;

  __asm__ __volatile__ ("inb %w1,%0":"=a" (v):"Nd" (port));
  return v;
}
void clrscr()
{
	int i; int j;
	for (i=0;i<NUM_COLUMNS;i++)
		for (j=0;j<NUM_ROWS;j++)
			printc_xy(i,j,' ');
	x = 0;
	y = 1;
}

void printc(char c)
{
  if ('\n' == c)
	{
		int i;		for (i=x;i<NUM_COLUMNS;i++)
		{
			printc(' ');		
		}
	}
  else
  {
  Word ch = (Word) (c & 0x00FF) | 0x0200;
  DWord screen = 0xb8000 + (y * NUM_COLUMNS + x) * 2;
  __asm__ __volatile__ ( "movb %0, %%al; outb $0xe9" ::"a"(c));
	
  if (++x >= NUM_COLUMNS)
  {
  	x = 0;
  	if (++y >= NUM_ROWS-1)
  		y = 1;
  }
  asm("movw %0, (%1)" : : "r"(ch), "r"(screen));
  }
}

void printk(char *string)
{
  int i;
  for (i = 0; string[i]; i++)
  	printc(string[i]);
  
}

void printk_xy(Byte column, Byte row, char *string)
{ 
  Byte saved_colum=x;
  Byte saved_row=y;
  x=column;
  y=row;
  printk(string);
  x=saved_colum;
  y=saved_row;
}	

void printc_xy(Byte column, Byte row, char ch)
{ 
  Byte saved_colum=x;
  Byte saved_row=y;
  x=column;
  y=row;
  printc(ch);
  x=saved_colum;
  y=saved_row;
}	

void print_clock(int tics){
	int x_pos = 74;
	int y_pos = 0;

	int min = 0;
	int sec = 0;
	char clock[] = {'0','0',':','0','0','\0'};
	char* buf = 0;

	if ((tics>17)&&(tics%18) == 0)
	{
		sec = tics/18;

		min = sec/60;
		sec = sec%60;

		itoa(min,buf);

		if (min==0) {clock[0]='0';clock[1]='0';}
		else if (min<10)
		{
			clock[0]='0'; clock[1]=buf[0];
		}
		else
		{
			clock[0]=buf[0];clock[1]=buf[1];
		}
		itoa(sec,buf);

		if (sec==0){clock[3]='0';clock[4]='0';}
		if (sec<10)
		{
			clock[3]='0'; clock[4]=buf[0];
		}
		else
		{
			clock[3]=buf[0];clock[4]=buf[1];
		}

		printk_xy(x_pos, y_pos, clock);

	}
}

void print_key (Byte code)
{
	int x_pos = 78;
	int y_pos = 24;   
	if (code=='\0') 
	printk_xy(x_pos-6, y_pos, "Control");
	else
	{
		printk_xy(x_pos-7,y_pos,"       ");
		printc_xy(x_pos,y_pos,code);
	}
}

void itoa(int num,char *buffer)
{
    int n = num;
    int k = 0; 
	
	if (num == 0)
	{
		buffer[0]='0';
		buffer[1]='\0';
	}
	else
	{
  
		while (n>0) //checking how many digits there are
		{
			n = n/10;
			k++;		}
  
    	for (n=k;n>0;n--)
    	{
      		buffer[n-1] = num%10+'0'; 
      		num = num/10;
    	}
    	buffer[k]='\0';
	}
}



